package dtn.supports;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import dtn.models.News;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

	public static Map<String, Integer> Max = new HashMap<String, Integer>();

	static String DB_News = "DTNews";
	public static String Table_TinMoi = "TinMoi";
	public static String Table_KhoaHoc = "KhoaHoc";
	public static String Table_ViecLam = "ViecLam";

	static String Field_ID = "ID";
	static String Field_Title = "TITLE";
	static String Field_ImageUrl = "IMAGE_URL";
	static String Field_ViewUrl = "VIEW_URL";
	static String Field_ContentHot = "CONTENT_HOT";
	static String Field_ContentDetail = "CONTENT_DETAIL";
	static String Field_Saved = "SAVED";

	public DatabaseHelper(Context context) {
		super(context, DB_News, null, 2);

		Max.put(Table_TinMoi, Settings.Max_TinMoi);
		Max.put(Table_KhoaHoc, Settings.Max_KhoaHoc);
		Max.put(Table_ViecLam, Settings.Max_ViecLam);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String sqlCreateTable;
		sqlCreateTable = "CREATE TABLE IF NOT EXISTS %s ("
				+ "ID STRING PRIMARY KEY," + "TITLE TEXT," + "IMAGE_URL TEXT,"
				+ "VIEW_URL TEXT UNIQUE," + "CONTENT_HOT TEXT,"
				+ "CONTENT_DETAIL TEXT," + "SAVED NUMERIC" + ")";
		db.execSQL(String.format(sqlCreateTable, Table_TinMoi));
		db.execSQL(String.format(sqlCreateTable, Table_KhoaHoc));
		db.execSQL(String.format(sqlCreateTable, Table_ViecLam));
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String sqlDropTable;
		sqlDropTable = "DROP TABLE IF EXISTS %s";

		db.execSQL(String.format(sqlDropTable, Table_TinMoi));
		db.execSQL(String.format(sqlDropTable, Table_KhoaHoc));
		db.execSQL(String.format(sqlDropTable, Table_ViecLam));
	}

	/**
	 * 
	 * @param tableName
	 * @param news
	 * @param isSaved
	 */
	public void insertRecord(String tableName, News news, boolean isSaved) {
		if (getNumOfRecords(tableName) >= Max.get(tableName))
			return;
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues contentValues = new ContentValues();

		try {
			contentValues.put(Field_ID, news.getId());
			contentValues.put(Field_Title, news.getTitle());
			contentValues.put(Field_ContentHot, news.getContent());
			contentValues.put(Field_ImageUrl, news.getIconUrl());
			contentValues.put(Field_ViewUrl, news.getViewUrl());
			if (isSaved) {
				contentValues.put(Field_Saved, 1);
			} else {
				contentValues.put(Field_Saved, 0);
			}
			contentValues.put(Field_ContentDetail, news.getContentDetail());

			db.insert(tableName, null, contentValues);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			db.close();
		}
	}

	/**
	 * 
	 * @param tableName
	 * @param news
	 */
	public void deleteRecord(String tableName, News news) {
		SQLiteDatabase db = this.getWritableDatabase();
		String[] args = { String.valueOf(news.getId()) };

		db.delete(tableName, String.format("%s=?", Field_ID), args);
		db.close();
	}

	/**
	 * 
	 * @param tableName
	 */
	public void deleteAllRecord(String tableName) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("DELETE FROM " + tableName);
		db.close();
	}

	/**
	 * 
	 * @param tableName
	 * @return
	 */
	public ArrayList<News> getAllList(String tableName) {
		SQLiteDatabase db = this.getWritableDatabase();
		ArrayList<News> res = new ArrayList<News>();
		String sqlSelect = "SELECT * FROM %s ORDER BY ID DESC";

		Cursor cursor = db.rawQuery(String.format(sqlSelect, tableName), null);
		if (cursor.getCount() != 0) {
			if (cursor.moveToFirst()) {
				do {
					News news = new News(cursor.getString(cursor
							.getColumnIndex(Field_ID)), cursor.getString(cursor
							.getColumnIndex(Field_Title)),
							cursor.getString(cursor
									.getColumnIndex(Field_ContentHot)),
							cursor.getString(cursor
									.getColumnIndex(Field_ImageUrl)),
							cursor.getString(cursor
									.getColumnIndex(Field_ViewUrl)),
							cursor.getString(cursor
									.getColumnIndex(Field_ContentDetail)));
					res.add(news);
				} while (cursor.moveToNext());
			}
		}
		cursor.close();
		db.close();
		return res;
	}

	/**
	 * 
	 * @param tableName
	 * @param listNews
	 */
	public void insertAllList(final String tableName,
			final ArrayList<News> listNews) {
		Thread thread = new Thread() {
			public void run() {
				deleteAllRecord(Table_TinMoi);
				deleteAllRecord(tableName);
				for (News news : listNews) {
					insertRecord(tableName, news, false);
				}
			}
		};
		thread.start();
	}

	/**
	 * 
	 * @param tableName
	 */
	public int getNumOfRecords(String tableName) {
		SQLiteDatabase db = this.getWritableDatabase();
		String sqlCount = "SELECT COUNT(ID) FROM %s";
		int res = 0;

		Cursor cursor = db.rawQuery(String.format(sqlCount, tableName), null);
		if (cursor.getCount() != 0) {
			if (cursor.moveToFirst()) {
				res = cursor.getInt(0);
			}
		}

		db.close();
		return res;
	}
}
